#ifndef APP_DATA_TIME_H
#define APP_DATA_TIME_H

#include "thread/threading.h"
#include "kernel/sign_kernel.h"
#include <iostream>
#include <mutex>

typedef enum _TIME_CHANGE_EVENT{
    SECOND_CHANGE,
    MINUTE_CHANGE,
    HOUR_CHANGE,
} TIME_CHANGE_EVENT;

class DataTime
{
public:
    int mYear = 2000;
    int mMonth = 1;
    int mDay = 1;
    int mHour = 8;
    int mMin = 0;
    int mSec = 0;
    static DataTime* getInstance();
    bool setDateTime(unsigned int hour, unsigned int min);
    bool setDateTime(unsigned int year, unsigned int mon, unsigned day, unsigned int hour, unsigned int min, unsigned int sec);
    bool setTimedPeriod(int timedPeriod);
    void timerTrigger(void* arg);
    std::string getTimeString(void);
    void syncTime(void);
private:
    bool firstTrigger = true;
    bool mRtcIsRunning = false;
    static DataTime* instance;
   
    DataTime(/* args */);
    ~DataTime();
    void timer_log();
    void addOneScond();
    bool isMonthEnd();
    bool isLeapYear();
protected:
    class RtcThread : public Thread {
    private:
        std::mutex mutex;
    public:
        DataTime* data = nullptr;
        RtcThread(DataTime* data) :data(data) {}
        ~RtcThread() {}
        void threadMain(uint32_t arg) {
            if (mutex.try_lock()) {/* 防止同一时间执行多次 */
                if (data->rtcIsRunning()) {
                    data->mRtcIsRunning = true;
                    systemNoBlock("hwclock -s");/* 同步硬件时间到系统时间 */
                } else {
                    data->mRtcIsRunning = false;
                }
                mutex.unlock();
            }
        }
    };
    RtcThread* rtcThread = nullptr;
    int mTimedPeriod;
    bool rtcIsRunning();
};

#endif